package pl.bristleback.chat.actions;

import org.apache.log4j.Logger;
import org.jwebsocket.api.WebSocketConnector;
import org.jwebsocket.token.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import pl.bristleback.chat.services.UsersService;
import pl.bristleback.chat.utils.SendMessageSupport;
import pl.bristleback.chat.vo.User;
import pl.bristleback.server.bristle.actions.AnnotatedRemoteAction;
import pl.bristleback.server.bristle.actions.RemoteAction;
import pl.bristleback.server.bristle.utils.BristleTokenFactory;

/**
 * //@todo class description
 * <p/>
 * Created on: 13.04.11 19:14 <br/>
 *
 * @author Paweł Machowski
 */
@Controller
@AnnotatedRemoteAction(actionName = "sendText")
public class SendTextAction implements RemoteAction {
  private static Logger log = Logger.getLogger(SendTextAction.class.getName());

  @Autowired
  private SendMessageSupport sender;

  @Autowired
  private UsersService usersService;

  @Override
  public void performAction(WebSocketConnector webSocketConnector, Token token) {
    String message = token.getString("text");
    boolean isMessageCompleted = token.getBoolean("isFinished");

    Token sendToken = BristleTokenFactory.createToken("partialText");
    if(isMessageCompleted){
      sendToken.setType("newText");
    }
    User currentUser = usersService.getUserByConnectorId(webSocketConnector.getId());
    sendToken.setString("username", currentUser.getName());
    sendToken.setString("id", currentUser.getId());
    sendToken.setString("text", message);

    sender.broadcastLogged(sendToken);

  }
}